  

ALTER TABLE "PharmacyProduct" ALTER COLUMN "GenericName" type text; 

----------------------------------------------------------------------------------------------------------------------

-- FUNCTION: public.widget_Table_PharmacyRetailStockProducts_UnderROL(integer, integer, text);

 DROP FUNCTION IF EXISTS public."widget_Table_PharmacyRetailStockProducts_UnderROL"(integer, integer, text);

CREATE OR REPLACE FUNCTION public."widget_Table_PharmacyRetailStockProducts_UnderROL"(
	"accountId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer,
	"retailStore" text DEFAULT NULL::text)
    RETURNS TABLE("ProductName" character varying, "GenericName" text, "ROL" integer, "RetailName" text, "AvailableQty" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

select * from ( SELECT 
               PP."ProductName",
	PP."GenericName",
	PPD."ROL",
	rp."RetailName", SUM(PS."QuantityIn") -sum(PS."QuantityOut") as "AvailableQty"
	                                    FROM "PharmacyRetailStock" PS  
	                                    join "PharmacyProduct" PP on PP."PharmacyProductId" = PS."PharmacyProductId"
                                        join "RetailWareHouseLink" rwhl ON rwhl."RetailWareHouseLinkId" = PS."RetailWareHouseLinkId"                                         
                                        join "RetailPharmacy" rp on rp."RetailPharmacyId" = rwhl."RetailPharmacyId" 
	                                    join "PharmacyWareHouse" pwh on pwh."PharmacyWareHouseId" = rwhl."PharmacyWareHouseId" 
                                        join "PharmacyProductDetail" PPD on PPD."PharmacyProductId" = PS."PharmacyProductId" and PPD."ROL" is not null
                                        left JOIN "PharmacyRetailUser" PRU ON PRU."RetailPharmacyId"=RP."RetailPharmacyId"
               
WHERE
	 (PS."QuantityIn" - PS."QuantityOut") > 0 and 
 	 case when "retailStore" is null then 1=1 else RP."RetailName"="retailStore" end
 	AND case when "accountId" is null then 1=1 else PRU."AccountId"="accountId" end  and
   case when "locationId" is null then 1=1 else pwh."LocationId" = "locationId" end 
	group by PP."ProductName",PP."GenericName",rp."RetailName",PPD."ROL",PRU."AccountId")a 
	where A."ROL" >= A."AvailableQty"
;
													 
end
$BODY$;

ALTER FUNCTION public."widget_Table_PharmacyRetailStockProducts_UnderROL"(integer, integer, text)
    OWNER TO postgres;

---------------------------------------------------------------------------------------------------------------------------------------------------------------

